
#include "Clientstdafx.h"
#include "ClientRoot.h"
#include "Math/stringConverter.h"
 
namespace Apo
{
//-----------------------------------------------------------------------------------------
String ClientRoot::CreateUniqueID(String n1, String n2)
{
    String tail;// = StringConverter::toString(++m_ObjCounter);
//     if(n2 != "")
//     {
//         while(FindObject(n1 + tail) || FindObject(n2 + tail))
//         {
//             tail = StringConverter::toString(++m_ObjCounter);
//         }
//     }
//     else
//     {
//         while(FindObject(n1 + tail))
//         {
//             tail = StringConverter::toString(++m_ObjCounter);
//         }
//     }
    return tail;
}
//-----------------------------------------------------------------------------------------
// Light::LightTypes ClientRoot::ConvertLightType(String val)
// {
//     if(val == "LT_DIRECTIONAL")
//         return Light::LT_DIRECTIONAL;
//     else if(val == "LT_SPOTLIGHT")
//         return Light::LT_SPOTLIGHT;
//     else
//         return Light::LT_POINT;
// }
//-----------------------------------------------------------------------------------------
// void ClientRoot::GetMeshInformationEx(const MeshPtr mesh,
//                                          size_t &vertex_count,
//                                          Vector3* &vertices,
//                                          size_t &index_count,
//                                          unsigned long* &indices,
//                                          const Vector3 &position,
//                                          const Quaternion &orient,
//                                          const Vector3 &scale)
// {
//     bool added_shared = false;
//     size_t current_offset = 0;
//     size_t shared_offset = 0;
//     size_t next_offset = 0;
//     size_t index_offset = 0;
// 
//     vertex_count = index_count = 0;
// 
//     // Calculate how many vertices and indices we're going to need
//     for (unsigned short i = 0; i < mesh->getNumSubMeshes(); ++i)
//     {
//         SubMesh* submesh = mesh->getSubMesh( i );
// 
//         // We only need to add the shared vertices once
//         if(submesh->useSharedVertices)
//         {
//             if( !added_shared )
//             {
//                 vertex_count += mesh->sharedVertexData->vertexCount;
//                 added_shared = true;
//             }
//         }
//         else
//         {
//             vertex_count += submesh->vertexData->vertexCount;
//         }
// 
//         // Add the indices
//         index_count += submesh->indexData->indexCount;
//     }
// 
// 
//     // Allocate space for the vertices and indices
//     vertices = new Vector3[vertex_count];
//     indices = new unsigned long[index_count];
// 
//     added_shared = false;
// 
//     // Run through the submeshes again, adding the data into the arrays
//     for ( unsigned short i = 0; i < mesh->getNumSubMeshes(); ++i)
//     {
//         SubMesh* submesh = mesh->getSubMesh(i);
// 
//         VertexData* vertex_data = submesh->useSharedVertices ? mesh->sharedVertexData : submesh->vertexData;
// 
//         if((!submesh->useSharedVertices)||(submesh->useSharedVertices && !added_shared))
//         {
//             if(submesh->useSharedVertices)
//             {
//               added_shared = true;
//               shared_offset = current_offset;
//             }
// 
//             const VertexElement* posElem = vertex_data->vertexDeclaration->findElementBySemantic(VES_POSITION);
// 
//             HardwareVertexBufferSharedPtr vbuf = vertex_data->vertexBufferBinding->getBuffer(posElem->getSource());
// 
//             unsigned char* vertex = static_cast<unsigned char*>(vbuf->lock(HardwareBuffer::HBL_READ_ONLY));
// 
//             // There is _no_ baseVertexPointerToElement() which takes an Real or a double
//             //  as second argument. So make it float, to avoid trouble when Real will
//             //  be comiled/typedefed as double:
//             //      Real* pReal;
//             float* pReal;
// 
//             for( size_t j = 0; j < vertex_data->vertexCount; ++j, vertex += vbuf->getVertexSize())
//             {
//                 posElem->baseVertexPointerToElement(vertex, &pReal);
// 
//                 Vector3 pt(pReal[0], pReal[1], pReal[2]);
// 
//                 vertices[current_offset + j] = (orient * (pt * scale)) + position;
//             }
// 
//             vbuf->unlock();
//             next_offset += vertex_data->vertexCount;
//         }
// 
// 
//         IndexData* index_data = submesh->indexData;
//         size_t numTris = index_data->indexCount / 3;
//         HardwareIndexBufferSharedPtr ibuf = index_data->indexBuffer;
// 
//         bool use32bitindexes = (ibuf->getType() == HardwareIndexBuffer::IT_32BIT);
// 
//         unsigned long*  pLong = static_cast<unsigned long*>(ibuf->lock(HardwareBuffer::HBL_READ_ONLY));
//         unsigned short* pShort = reinterpret_cast<unsigned short*>(pLong);
// 
//         size_t offset = (submesh->useSharedVertices)? shared_offset : current_offset;
// 
//         if ( use32bitindexes )
//         {
//             for ( size_t k = 0; k < numTris*3; ++k)
//             {
//                 indices[index_offset++] = pLong[k] + static_cast<unsigned long>(offset);
//             }
//         }
//         else
//         {
//             for ( size_t k = 0; k < numTris*3; ++k)
//             {
//                 indices[index_offset++] = static_cast<unsigned long>(pShort[k]) + static_cast<unsigned long>(offset);
//             }
//         }
// 
//         ibuf->unlock();
//         current_offset = next_offset;
//     }
// }
//-----------------------------------------------------------------------------------------
// bool ClientRoot::PickEntity(RaySceneQuery* mRaySceneQuery, Ray &ray, Entity **result, Vector3 &hitpoint)
// {
//     mRaySceneQuery->setRay(ray);
//     mRaySceneQuery->setQueryMask(QUERYFLAG_MOVABLE);
//     mRaySceneQuery->setSortByDistance(true);
// 
//     if (mRaySceneQuery->execute().size() <= 0) return (false);
// 
//     // at this point we have raycast to a series of different objects bounding boxes.
//     // we need to test these different objects to see which is the first polygon hit.
//     // there are some minor optimizations (distance based) that mean we wont have to
//     // check all of the objects most of the time, but the worst case scenario is that
//     // we need to test every triangle of every object.
//     Real closest_distance = -1.0f;
//     Vector3 closest_result;
//     RaySceneQueryResult &query_result = mRaySceneQuery->getLastResults();
//     for (size_t qr_idx = 0; qr_idx < query_result.size(); qr_idx++)
//     {
//         // stop checking if we have found a raycast hit that is closer
//         // than all remaining entities
//         if ((closest_distance >= 0.0f) && (closest_distance < query_result[qr_idx].distance))
//         {
//             break;
//         }
// 
//         // only check this result if its a hit against an entity
//         if ((query_result[qr_idx].movable != NULL) && (query_result[qr_idx].movable->getMovableType().compare("Entity") == 0))
//         {
//             // get the entity to check
//             Entity *pentity = static_cast<Entity*>(query_result[qr_idx].movable);
// 
//             if(!pentity->getVisible()) continue;
//             // mesh data to retrieve
//             size_t vertex_count;
//             size_t index_count;
//             Vector3 *vertices;
//             unsigned long *indices;
// 
//             // get the mesh information
//             GetMeshInformationEx(pentity->getMesh(), vertex_count, vertices, index_count, indices,
// 	                                 pentity->getParentNode()->_getDerivedPosition(),
//                                      pentity->getParentNode()->_getDerivedOrientation(),
//                                      pentity->getParentNode()->_getDerivedScale());
// 
//             // test for hitting individual triangles on the mesh
//             bool new_closest_found = false;
//             for (int i = 0; i < static_cast<int>(index_count); i += 3)
//             {
//                 // check for a hit against this triangle
//                 std::pair<bool, Real> hit = Math::intersects(ray, vertices[indices[i]],
//                          vertices[indices[i+1]], vertices[indices[i+2]], true, false);
// 
//                 // if it was a hit check if its the closest
//                 if (hit.first)
//                 {
//                     if ((closest_distance < 0.0f) || (hit.second < closest_distance))
//                     {
//                         // this is the closest so far, save it off
//                         closest_distance = hit.second;
//                         new_closest_found = true;
//                     }
//                 }
//             }
// 
//             // free the verticies and indicies memory
//             delete[] vertices;
//             delete[] indices;
// 
//             // if we found a new closest raycast for this object, update the
//             // closest_result before moving on to the next object.
//             if (new_closest_found)
//             {
//                 closest_result = ray.getPoint(closest_distance);
// 	            (*result) = pentity;
//             }
//         }
//     }
// 
//     // return the result
//     if (closest_distance >= 0.0f)
//     {
//         hitpoint = closest_result;
//         return (true);
//     }
//     else
//     {
//         // raycast failed
//         return (false);
//     }
// }
//-----------------------------------------------------------------------------------------
// bool ClientRoot::PickWidget(RaySceneQuery* mRaySceneQuery, Ray &ray, int &Axis)
// {
//     mRaySceneQuery->setRay(ray);
//     mRaySceneQuery->setSortByDistance(true);
//     mRaySceneQuery->setQueryMask(QUERYFLAG_WIDGET);
// 
//     if (mRaySceneQuery->execute().size() <= 0) return (false);
// 
//     // at this point we have raycast to a series of different objects bounding boxes.
//     // we need to test these different objects to see which is the first polygon hit.
//     // there are some minor optimizations (distance based) that mean we wont have to
//     // check all of the objects most of the time, but the worst case scenario is that
//     // we need to test every triangle of every object.
//     Real closest_distance = -1.0f;
//     Vector3 closest_result;
//     RaySceneQueryResult &query_result = mRaySceneQuery->getLastResults();
//     for (size_t qr_idx = 0; qr_idx < query_result.size(); qr_idx++)
//     {
//         // stop checking if we have found a raycast hit that is closer
//         // than all remaining entities
//         if ((closest_distance >= 0.0f) && (closest_distance < query_result[qr_idx].distance))
//         {
//             break;
//         }
// 
//         // only check this result if its a hit against an entity
//         if ((query_result[qr_idx].movable != NULL) && (query_result[qr_idx].movable->getMovableType().compare("Entity") == 0))
//         {
//             // get the entity to check
//             Entity *pentity = static_cast<Entity*>(query_result[qr_idx].movable);
// 
//             size_t vertex_count;
//             size_t index_count;
//             Vector3 *vertices;
//             unsigned long *indices;
// 
//             // get the mesh information
//             GetMeshInformationEx(pentity->getMesh(), vertex_count, vertices, index_count, indices,
// 	                                 pentity->getParentNode()->_getDerivedPosition(),
//                                      pentity->getParentNode()->_getDerivedOrientation(),
//                                      pentity->getParentNode()->_getDerivedScale());
// 
//             // test for hitting individual triangles on the mesh
//             bool new_closest_found = false;
//             for (int i = 0; i < static_cast<int>(index_count); i += 3)
//             {
//                 // check for a hit against this triangle
//                 std::pair<bool, Real> hit = Math::intersects(ray, vertices[indices[i]],
//                 vertices[indices[i+1]], vertices[indices[i+2]], true, false);
//                 // if it was a hit check if its the closest
//                 if (hit.first)
//                 {
//                     if ((closest_distance < 0.0f) || (hit.second < closest_distance))
//                     {
//                         // this is the closest so far, save it off
//                         closest_distance = hit.second;
//                         new_closest_found = true;
//                     }
//                 }
//             }
// 
//             // free the verticies and indicies memory
//             delete[] vertices;
//             delete[] indices;
// 
//             // if we found a new closest raycast for this object, update the
//             // closest_result before moving on to the next object.
//             if (new_closest_found)
//             {
//                 closest_result = ray.getPoint(closest_distance);
// 	            String sName = pentity->getName();
// 	            if(sName.substr(0,5) == "scbwx") Axis = AXIS_X;
//                 else if(sName.substr(0,5) == "scbwz") Axis = AXIS_Z;
// 	            else if(sName.substr(0,5) == "scbwy") Axis = AXIS_Y;
//             }
//         }
//     }
// 
//     return (closest_distance >= 0.0f);
// }
//-----------------------------------------------------------------------------------------
// bool ClientRoot::WorldIntersect(RaySceneQuery* mRaySceneQuery, Ray &ray, Vector3 &hitposition)
// {
//     mRaySceneQuery->setRay(ray);
//     mRaySceneQuery->setQueryTypeMask(SceneManager::WORLD_GEOMETRY_TYPE_MASK);
//     mRaySceneQuery->setWorldFragmentType(SceneQuery::WFT_SINGLE_INTERSECTION);
//     RaySceneQueryResult& qryResult = mRaySceneQuery->execute();
//     RaySceneQueryResult::iterator i = qryResult.begin();
//     if (i != qryResult.end() && i->worldFragment)
//     {
//         hitposition = i->worldFragment->singleIntersection;
// 	    return true;
//     }
//     return false;
// }
//----------------------------------------------------------------------------------------
// Plane ClientRoot::FindGizmoTranslationPlane(Ray &pickRay, int TranslationAxis)
// {
//     Quaternion qOrient = m_SelectedEditor->GetDerivedOrientation();
//     Vector3 vPos = m_SelectedEditor->GetDerivedPosition();
//     Vector3 vCamBack = GetViewport()->GetCameraEditor()->GetCamera()->getDerivedDirection();
//     vCamBack = -vCamBack;
//     //if(!TranslationAxis) return Plane(vCamBack,vPos);
//     if(!TranslationAxis) return Plane(qOrient.yAxis(), vPos);
// 
//     Plane planeX(qOrient.xAxis(), vPos);
//     Plane planeY(qOrient.yAxis(), vPos);
//     Plane planeZ(qOrient.zAxis(), vPos);
// 
//     float vX = planeX.projectVector(pickRay.getDirection()).length();
//     float vY = planeY.projectVector(pickRay.getDirection()).length();
//     float vZ = planeZ.projectVector(pickRay.getDirection()).length();
// 
//     if(TranslationAxis & AXIS_X) vX = 10000.0f;
//     if(TranslationAxis & AXIS_Y) vY = 10000.0f;
//     if(TranslationAxis & AXIS_Z) vZ = 10000.0f;
// 
//     if (vX < vY && vX < vZ)
//         return planeX;
//     else
//     {
//         if (vY < vX && vY < vZ )
//             return planeY;
//         else
//             return planeZ;
//     }
// }
// //--------------------------------------------------------------------------------
// Vector3 ClientRoot::GetGizmoIntersect(Ray &pickRay, Plane &planetouse, int TranslationAxis, Vector3 &vLastPosition)
// {
//     std::pair<bool,Real> result;
// 
//     result = pickRay.intersects(planetouse);
// 
//     if (result.first)
//     {
//         Vector3 AxisX = Vector3::ZERO;
//         Vector3 AxisY = Vector3::ZERO;
//         Vector3 AxisZ = Vector3::ZERO;
// 
//         if(TranslationAxis)
//         {
//             if(TranslationAxis & AXIS_X) AxisX = m_SelectedEditor->GetDerivedOrientation().xAxis();
//             if(TranslationAxis & AXIS_Y) AxisY = m_SelectedEditor->GetDerivedOrientation().yAxis();
//             if(TranslationAxis & AXIS_Z) AxisZ = m_SelectedEditor->GetDerivedOrientation().zAxis();
//         }
//         else
//         {
//             AxisX = m_SelectedEditor->GetDerivedOrientation().xAxis();
//             AxisZ = m_SelectedEditor->GetDerivedOrientation().zAxis();
//         }
// 
//         Vector3 Proj = pickRay.getPoint(result.second) - vLastPosition;
//         Vector3 vPos1 = (AxisX.dotProduct(Proj) * AxisX);
//         Vector3 vPos2 = (AxisY.dotProduct(Proj) * AxisY);
//         Vector3 vPos3 = (AxisZ.dotProduct(Proj) * AxisZ);
//         Vector3 vPos = vPos1 + vPos2 + vPos3;
// 
//         m_LastTranslationDelta = vPos;
//         return vPos;
//     }
//     return m_LastTranslationDelta;
// }
// //-----------------------------------------------------------------------------------------
// void ClientRoot::FillResourceGroup(ResourceGroupManager *mngr,StringVector &list,String path,String group)
// {
//     String strTemp;
//     unsigned int itemcount;
//     String stype;
// 
//     itemcount = list.size();
// 
//     for(unsigned int i = 0;i < itemcount;i++)
//     {
// 	    strTemp = list[i];
// 	    if(strTemp.substr(0,3) == "FS:") stype = "FileSystem";
// 	    else if(strTemp.substr(0,3) == "ZP:") stype = "Zip";
// 	    strTemp.erase(0,3);
// 	    if(strTemp.find(".") == 0)
// 	    {
// 	        strTemp = path + "/" + strTemp;
//             strTemp = m_System->QualifyPath(strTemp);
// 	    }
// #if OGRE_PLATFORM == OGRE_PLATFORM_LINUX
//         strTemp = '/' + strTemp + '/';
// #endif
//         std::cout << "Path: " << strTemp << std::endl;
//  	    mngr->addResourceLocation(strTemp,stype,group);
//     }
// }
// //-----------------------------------------------------------------------------------------
// void ClientRoot::WriteCameraPositions(std::ostream &outstream, bool addcurrent)
// {
//     char savestr[500];
//     int i;
//     sprintf_s(savestr,500,"  <CAMERAPOSITIONS count=\"%d\">\n",m_ProjectOptions.CameraSaveCount);
//     outstream << savestr;
//     for(i =0;i < m_ProjectOptions.CameraSaveCount;i++)
// 	{
// 	    sprintf_s(savestr,500,"    <OPTION id=\"%d\" position=\"%s\" orientation=\"%s\"></OPTION>\n",i,StringConverter::toString(m_ProjectOptions.CameraPositions[i]).c_str(),StringConverter::toString(m_ProjectOptions.CameraOrientations[i]).c_str());
//         outstream << savestr;
// 	}
//     if(addcurrent)
//     {
//         Vector3 vCamPos = GetViewport()->GetCameraEditor()->GetCamera()->getDerivedPosition();
//         Quaternion qCamOrient = GetViewport()->GetCameraEditor()->GetCamera()->getDerivedOrientation();
// 	    sprintf_s(savestr,500,"    <OPTION id=\"%d\" position=\"%s\" orientation=\"%s\"></OPTION>\n",i,StringConverter::toString(vCamPos).c_str(),StringConverter::toString(qCamOrient).c_str());
//         outstream << savestr;
//     }
//     else
//     {
//         sprintf_s(savestr,500,"    <OPTION id=\"%d\" position=\"5 10 5\" orientation=\"0.937683 -0.155887 -0.306458 -0.050973\"></OPTION>\n",i);
//         outstream << savestr;
//     }
//     outstream << "  </CAMERAPOSITIONS>\n";
// }
// //-----------------------------------------------------------------------------------------
// void ClientRoot::WriteProjectOptions(std::ostream &outstream, bool newproject)
// {
//     char buffer[5000];
//     unsigned int i;
// 
//     PROJECTOPTIONS *pOpt = GetProjectOptions();
// 
//     outstream << "  <PROJECT>\n";
//     sprintf_s(buffer,5000,"    <SCENEMANAGER value=\"%s\"></SCENEMANAGER>\n",pOpt->SceneManagerName.c_str());
//     outstream << buffer;
//     sprintf_s(buffer,5000,"    <ETLDIR value=\"%s\"></ETLDIR>\n",pOpt->ETLDirectory.c_str());
//     outstream << buffer;
//     sprintf_s(buffer,5000,"    <HYDRAXDIR value=\"%s\"></HYDRAXDIR>\n",pOpt->HydraxDirectory.c_str());
//     outstream << buffer;
//     sprintf_s(buffer,5000,"    <CAELUMDIR value=\"%s\"></CAELUMDIR>\n",pOpt->CaelumDirectory.c_str());
//     outstream << buffer;
//     sprintf_s(buffer,5000,"    <PAGEDGEOMETRYDIR value=\"%s\"></PAGEDGEOMETRYDIR>\n",pOpt->PagedGeometryDirectory.c_str());
//     outstream << buffer;
//     outstream << "    <RESOURCEDIRECTORIES>\n";
//     String strtype;
//     String value;
//     for(i = 0;i < pOpt->ResourceDirectories.size();i++)
//     {
//         value = pOpt->ResourceDirectories[i];
//         if(value.substr(0,3) == "FS:")
//             strtype = "FileSystem";
//         else if(value.substr(0,3) == "ZP:")
//             strtype = "Zip";
//         else strtype = "Unknown";
//         value.erase(0,3);
//         sprintf_s(buffer,5000,"      <DIRECTORY type=\"%s\" value=\"%s\"></DIRECTORY>\n",strtype.c_str(),value.c_str());
//         outstream << buffer;
//     }
//     outstream << "    </RESOURCEDIRECTORIES>\n";
// 
//     WriteCameraPositions(outstream,!newproject);
//     outstream << "  </PROJECT>\n";
// }
//-----------------------------------------------------------------------------------------
void ClientRoot::AdjustUserResourceDirectories(String oldpath)
{
//     unsigned int i;
//     String typestr;
//     String value;
// 
//     String newdir = m_ProjectOptions.ProjectDir;
//     String result;
// 
//     for(i = 0;i < m_ProjectOptions.ResourceDirectories.size();i++)
//     {
//         value = m_ProjectOptions.ResourceDirectories[i];
//         typestr = value.substr(0,3);
//         value.erase(0,3);
//         if(value.substr(0,1) == "." && value.substr(1,1) != ".") 
//             continue;
//         String pathto = value;
//         if(value.substr(0,2) == "..") 
//             value = oldpath + "/" + value;
//         result = m_System->GetRelativePath(newdir,pathto);
//         m_ProjectOptions.ResourceDirectories[i] = typestr + result;
//     }
}
//----------------------------------------------------------------------------
// void ClientRoot::VolumeSelect(Ray &topLeft, Ray &topRight, Ray &bottomLeft, Ray &bottomRight, NameObjectPairList &result)
// {
//     PlaneBoundedVolume vol;
//     vol.planes.push_back(Plane(topLeft.getPoint(3), topRight.getPoint(3), bottomRight.getPoint(3)));         // front plane
//     vol.planes.push_back(Plane(topLeft.getOrigin(), topLeft.getPoint(20), topRight.getPoint(20)));         // top plane
//     vol.planes.push_back(Plane(topLeft.getOrigin(), bottomLeft.getPoint(20), topLeft.getPoint(20)));       // left plane
//     vol.planes.push_back(Plane(bottomLeft.getOrigin(), bottomRight.getPoint(20), bottomLeft.getPoint(20)));   // bottom plane
//     vol.planes.push_back(Plane(topRight.getOrigin(), topRight.getPoint(20), bottomRight.getPoint(20)));     // right plane   
// 
//     PlaneBoundedVolumeList volList;
//     volList.push_back(vol);
// 
//     PlaneBoundedVolumeListSceneQuery *VolQuery = GetSceneManager()->createPlaneBoundedVolumeQuery(PlaneBoundedVolumeList());
//     VolQuery->setVolumes(volList);
//     VolQuery->setQueryMask(QUERYFLAG_MOVABLE);
//     SceneQueryResult qryresult = VolQuery->execute();
// 
//     result.clear();
//     SceneQueryResultMovableList::iterator itr;
//     for (itr = qryresult.movables.begin(); itr != qryresult.movables.end(); ++itr)
//     {
//         String objname = (*itr)->getName();
//         if(objname.substr(0,4) == "scbh")
//             objname.erase(0,4);
//         
//         CBaseEditor *object = FindObject(objname);
//         if(object)
//         {
//             result.insert(NameObjectPairList::value_type(object->GetName(),object));
//         }
//     }
// }
//-----------------------------------------------------------------------------------------
void ClientRoot::CreateWidgets()
{
//     m_WidgetNode = GetSceneManager()->getRootEditNode()->createChildEditNode("scbWidgetNode",Vector3(0,0,0),Quaternion::IDENTITY);
// 
//     m_WidgetX = m_WidgetNode->createChildEditNode("scbnwx",Vector3(0,0,0),Quaternion::IDENTITY);
//     m_WidgetY = m_WidgetNode->createChildEditNode("scbnwy",Vector3(0,0,0),Quaternion::IDENTITY);
//     m_WidgetZ = m_WidgetNode->createChildEditNode("scbnwz",Vector3(0,0,0),Quaternion::IDENTITY);
// 
//     m_WidgetX->yaw(Degree(-90));
//     m_WidgetY->pitch(Degree(90));
//     m_WidgetZ->yaw(Degree(180));
// 
//     //Entities
//     Entity* entityZ = GetSceneManager()->createEntity("scbwz", "scbArrowEx.mesh");
//     Entity* entityX = GetSceneManager()->createEntity("scbwx", "scbArrowEx.mesh");
//     Entity* entityY = GetSceneManager()->createEntity("scbwy", "scbArrowEx.mesh");
// 
//     //ZZ arrows
//     entityZ->setCastShadows(false);
//     entityZ->setMaterialName("mtSCBBLUE");
//     entityZ->setRenderQueueGroup(RENDER_QUEUE_OVERLAY - 1);
//     entityZ->setQueryFlags(QUERYFLAG_WIDGET);
//     m_WidgetZ->attachObject(entityZ);
// 
//     //XX arrows
//     entityX->setCastShadows(false);
//     entityX->setMaterialName("mtSCBRED");
//     entityX->setRenderQueueGroup(RENDER_QUEUE_OVERLAY - 1);
//     entityX->setQueryFlags(QUERYFLAG_WIDGET);
//     m_WidgetX->attachObject(entityX);
// 
//     //YY arrows
//     entityY->setCastShadows(false);
//     entityY->setMaterialName("mtSCBGREEN");
//     entityY->setRenderQueueGroup(RENDER_QUEUE_OVERLAY - 1);
//     entityY->setQueryFlags(QUERYFLAG_WIDGET);
//     m_WidgetY->attachObject(entityY);
// 
//     m_WidgetNode->setVisible(false);
}
//-----------------------------------------------------------------------------------------
void ClientRoot::UpdateWidgets()
{
//     if(!m_WidgetNode) 
//         return;
//     if(m_SelectedEditor && m_SelectedEditor->UsesGizmos() && m_SelectedEditor != GetViewport()->GetCameraEditor()) 
//     {
//         Vector3 position = m_SelectedEditor->GetDerivedPosition();
//         if(m_SelectedEditor->UsesHelper())
//             position = m_SelectedEditor->GetHelper()->GetNode()->_getDerivedPosition();
//         float distance = (position - GetViewport()->GetCameraEditor()->GetDerivedPosition()).length();
//         distance /= 30.0f;
//         
//         if(GetViewport())
//         {
//             Vector4 rect;
//             GetViewport()->GetRect(rect);
//             distance /= (rect.z / 800.0f);
//         }
//         
//         m_WidgetNode->setPosition(position);
//         m_WidgetNode->setOrientation(m_SelectedEditor->GetDerivedOrientation());
//         m_WidgetNode->setScale(distance,distance,distance);
//         m_WidgetNode->setVisible(true);
//     }
//     else
//     {
//         m_WidgetNode->setVisible(false);
//     }

 }
//-----------------------------------------------------------------------------------------
void ClientRoot::HiLiteWidget(int ID)
{
//     if(m_OldWidgetAxis == ID) 
//         return;
//     
//     m_OldWidgetAxis = ID;
//     Entity* wx = static_cast<Entity *>(m_WidgetX->getAttachedObject(0));
//     Entity* wy = static_cast<Entity *>(m_WidgetY->getAttachedObject(0));
//     Entity* wz = static_cast<Entity *>(m_WidgetZ->getAttachedObject(0));
// 
//     if(ID & AXIS_X)
//         wx->setMaterialName("mtSCBREDL");
//     else
//         wx->setMaterialName("mtSCBRED");
//     if(ID & AXIS_Y)
//         wy->setMaterialName("mtSCBGREENL");
//     else
//         wy->setMaterialName("mtSCBGREEN");
//     if(ID & AXIS_Z)
//         wz->setMaterialName("mtSCBBLUEL");
//     else
//         wz->setMaterialName("mtSCBBLUE");
}
//-----------------------------------------------------------------------------------------
void ClientRoot::SetWidgetMode(int mode)
{
//     if(m_OldWidgetMode == mode) 
//         return;
//     m_OldWidgetMode = mode;
//     Entity* wx = static_cast<Entity *>(m_WidgetX->getAttachedObject(0));
//     Entity* wy = static_cast<Entity *>(m_WidgetY->getAttachedObject(0));
//     Entity* wz = static_cast<Entity *>(m_WidgetZ->getAttachedObject(0));
// 
//     wx->getSubEntity(1)->setVisible(false);
//     wx->getSubEntity(2)->setVisible(false);
//     wx->getSubEntity(3)->setVisible(false);
//     wy->getSubEntity(1)->setVisible(false);
//     wy->getSubEntity(2)->setVisible(false);
//     wy->getSubEntity(3)->setVisible(false);
//     wz->getSubEntity(1)->setVisible(false);
//     wz->getSubEntity(2)->setVisible(false);
//     wz->getSubEntity(3)->setVisible(false);
//     switch(mode)
//     {
//     case TOOL_MOVE:
//         {
//             wx->getSubEntity(1)->setVisible(true);
//             wy->getSubEntity(1)->setVisible(true);
//             wz->getSubEntity(1)->setVisible(true);
//             break;
// 		}
//     case TOOL_ROTATE:
//         {
//             wx->getSubEntity(2)->setVisible(true);
//             wy->getSubEntity(2)->setVisible(true);
//             wz->getSubEntity(2)->setVisible(true);
//             break;
//         }
//     case TOOL_SCALE:
//         {
//             wx->getSubEntity(3)->setVisible(true);
//             wy->getSubEntity(3)->setVisible(true);
//             wz->getSubEntity(3)->setVisible(true);
//             break;
// 		}
//     }
}
//-----------------------------------------------------------------------------------------
void ClientRoot::DestroyWidgets()
{
//     if(!m_WidgetNode) 
//         return;
// 
//     Entity *dObj = static_cast<Entity*>(m_WidgetX->getAttachedObject(0));
//     m_WidgetNode->removeAndDestroyChild(m_WidgetX->getName());
//     dObj->_getManager()->destroyEntity(dObj);
//     dObj = static_cast<Entity*>(m_WidgetY->getAttachedObject(0));
//     m_WidgetNode->removeAndDestroyChild(m_WidgetY->getName());
//     dObj->_getManager()->destroyEntity(dObj);
//     dObj = static_cast<Entity*>(m_WidgetZ->getAttachedObject(0));
//     m_WidgetNode->removeAndDestroyChild(m_WidgetZ->getName());
//     dObj->_getManager()->destroyEntity(dObj);
// 
//     m_WidgetNode->getParentEditNode()->removeAndDestroyChild(m_WidgetNode->getName());
//     m_WidgetNode = 0;
//     m_WidgetX = 0;
//     m_WidgetY = 0;
//     m_WidgetZ = 0;
}
//-----------------------------------------------------------------------------------------
void ClientRoot::OnKeyDown (unsigned int key)
{
//     if(m_ActiveViewport)
//         m_ActiveViewport->OnKeyDown(key);
}
//-----------------------------------------------------------------------------------------
void ClientRoot::OnKeyUp (unsigned int key)
{
//     if(m_ActiveViewport)
//         m_ActiveViewport->OnKeyUp(key);
}
//-----------------------------------------------------------------------------------------
void ClientRoot::OnMouseWheel (Vector2 point, float delta, unsigned int buttons)
{
//     if(m_ActiveViewport)
//         m_ActiveViewport->OnMouseWheel(point, delta, buttons);
}
//-----------------------------------------------------------------------------------------
void ClientRoot::OnMouseMove (Vector2 point, unsigned int buttons)
{
//     if(!m_ActiveViewport)
//         return;
//     Vector4 rect;
//     m_ActiveViewport->GetRect(rect);
//     if((rect.x <= point.x) && (rect.y <= point.y) && ((rect.x + rect.z) >= point.x) && ((rect.y + rect.w) >= point.y))
//         m_ActiveViewport->OnMouseMove(point - Vector2(rect.x,rect.y), buttons);
//     else
//         m_ActiveViewport->OnMouseLeave(point - Vector2(rect.x,rect.y), buttons);
}
//-----------------------------------------------------------------------------------------
void ClientRoot::OnMouseLeave (Vector2 point, unsigned int buttons)
{
//     if(m_ActiveViewport)
//     {
//         Vector4 rect;
//         m_ActiveViewport->GetRect(rect);
//         m_ActiveViewport->OnMouseLeave(point - Vector2(rect.x,rect.y), buttons);
//     }
}
//-----------------------------------------------------------------------------------------
void ClientRoot::OnMouseLeftDown (Vector2 point, unsigned int buttons)
{
//     Vector4 rect;
//     NameObjectPairList viewports = GetObjectsByType(ETYPE_VIEWPORT);
//     NameObjectPairList::const_iterator it = viewports.begin();
// 
//     CViewportEditor *vp = 0;
//     int ZOrder = -1000;
//     while(it != viewports.end())
//     {
//         int order = static_cast<CViewportEditor*>(it->second)->GetRect(rect);
//         if((rect.x <= point.x) && (rect.y <= point.y) && ((rect.x + rect.z) >= point.x) && ((rect.y + rect.w) >= point.y) && (order > ZOrder))
//         {
//            ZOrder = order;
//            vp = static_cast<CViewportEditor*>(it->second);
//         }
//         it++;
//     }
//     if(vp)
//     {
//         m_ActiveViewport = vp;
//         m_ActiveViewport->GetRect(rect);
//         m_ActiveViewport->OnMouseLeftDown(point - Vector2(rect.x,rect.y), buttons);
//     }
}
//-----------------------------------------------------------------------------------------
void ClientRoot::OnMouseRightDown (Vector2 point, unsigned int buttons)
{
//     Vector4 rect;
//     NameObjectPairList viewports = GetObjectsByType(ETYPE_VIEWPORT);
//     NameObjectPairList::const_iterator it = viewports.begin();
// 
//     CViewportEditor *vp = 0;
//     int ZOrder = -1000;
//     while(it != viewports.end())
//     {
//         int order = static_cast<CViewportEditor*>(it->second)->GetRect(rect);
//         if((rect.x <= point.x) && (rect.y <= point.y) && ((rect.x + rect.z) >= point.x) && ((rect.y + rect.w) >= point.y) && (order > ZOrder))
//         {
//              ZOrder = order;
//              vp = static_cast<CViewportEditor*>(it->second);
//         }
//         it++;
//     }
//     if(vp)
//     {
//         m_ActiveViewport = vp;
//         m_ActiveViewport->GetRect(rect);
//         m_ActiveViewport->OnMouseRightDown(point - Vector2(rect.x,rect.y), buttons);
//     }
}
//-----------------------------------------------------------------------------------------
void ClientRoot::OnMouseMiddleDown (Vector2 point, unsigned int buttons)
{
//     Vector4 rect;
//     NameObjectPairList viewports = GetObjectsByType(ETYPE_VIEWPORT);
//     NameObjectPairList::const_iterator it = viewports.begin();
// 
//     CViewportEditor *vp = 0;
//     int ZOrder = -1000;
//     while(it != viewports.end())
//     {
//         int order = static_cast<CViewportEditor*>(it->second)->GetRect(rect);
//         if((rect.x <= point.x) && (rect.y <= point.y) && ((rect.x + rect.z) >= point.x) && ((rect.y + rect.w) >= point.y) && (order > ZOrder))
//         {
//             ZOrder = order;
//             vp = static_cast<CViewportEditor*>(it->second);
//         }
//         it++;
//     }
//     if(vp)
//     {
//         m_ActiveViewport = vp;
//         m_ActiveViewport->GetRect(rect);
//         m_ActiveViewport->OnMouseMiddleDown(point - Vector2(rect.x,rect.y), buttons);
//     }
}
//-----------------------------------------------------------------------------------------
void ClientRoot::OnMouseLeftUp (Vector2 point, unsigned int buttons)
{
//     if(!m_ActiveViewport)
//         return;
//     Vector4 rect;
//     m_ActiveViewport->GetRect(rect);
//     if((rect.x <= point.x) && (rect.y <= point.y) && ((rect.x + rect.z) >= point.x) && ((rect.y + rect.w) >= point.y))
//         m_ActiveViewport->OnMouseLeftUp(point - Vector2(rect.x,rect.y), buttons);
}
//-----------------------------------------------------------------------------------------
void ClientRoot::OnMouseMiddleUp (Vector2 point, unsigned int buttons)
{
//     if(!m_ActiveViewport)
//         return;
//     Vector4 rect;
//     m_ActiveViewport->GetRect(rect);
//     if((rect.x <= point.x) && (rect.y <= point.y) && ((rect.x + rect.z) >= point.x) && ((rect.y + rect.w) >= point.y))
//         m_ActiveViewport->OnMouseMiddleUp(point - Vector2(rect.x,rect.y), buttons);
}
//-----------------------------------------------------------------------------------------
void ClientRoot::OnMouseRightUp (Vector2 point, unsigned int buttons)
{
//     if(!m_ActiveViewport)
//         return;
//     Vector4 rect;
//     m_ActiveViewport->GetRect(rect);
//     if((rect.x <= point.x) && (rect.y <= point.y) && ((rect.x + rect.z) >= point.x) && ((rect.y + rect.w) >= point.y))
//         m_ActiveViewport->OnMouseRightUp(point - Vector2(rect.x,rect.y), buttons);
}
//-----------------------------------------------------------------------------------------
void ClientRoot::RenderWindowResized()
{
//     NameObjectPairList viewports = GetObjectsByType(ETYPE_VIEWPORT);
//     NameObjectPairList::const_iterator it = viewports.begin();
// 
//     while(it != viewports.end())
//     {
//         static_cast<CViewportEditor*>(it->second)->RenderWindowResized();
//         it++;
//     }
//     UpdateWidgets();
//     ClearScreenBackground(true);
}
//-----------------------------------------------------------------------------------------
}